package cn.frank.framework.king.rest;

import cn.frank.framework.king.conf.mvc.WebMvcResourceEnum;
import cn.frank.framework.king.domain.vo.Result;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @description: TODO
 * @author: renjiangyang
 * @date 2025/10/29 8:48:34
 * @since 1.8
 */
@Api(tags = "文件上传接口")
@RestController
@Slf4j
@RequestMapping("/api/file")
public class UploadController {


    @ApiOperation(value = "上传单个文件")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParam(name = "file", value = "上传文件", required = true, dataType = "MultipartFile")
    @PostMapping("/upload")
    public Result<String> upload(@RequestPart("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.fail("文件不能为空");
        }
        try {
            String uploadDir = getUploadDir();
            File dest = new File(uploadDir, file.getOriginalFilename());
            file.transferTo(dest);

            log.info("文件上传成功：{}", dest.getAbsolutePath());
            return Result.success("上传成功，存放路径：" + dest.getAbsolutePath());
        } catch (IOException e) {
            log.error("文件上传失败", e);
            return Result.fail("文件上传失败: " + e.getMessage());
        }
    }

    @ApiOperation(value = "上传多个文件")
    @ApiOperationSupport(order = 2)
    @PostMapping("/upload/multi")
    public Result<List<String>> uploadMulti(@RequestPart("files") MultipartFile[] files) {
        if (files == null || files.length == 0) {
            return Result.fail("文件不能为空");
        }

        List<String> results = new ArrayList<>();
        try {
            String uploadDir = getUploadDir();
            for (MultipartFile file : files) {
                if (file.isEmpty()) continue;
                File dest = new File(uploadDir, file.getOriginalFilename());
                file.transferTo(dest);
                results.add(dest.getAbsolutePath());
                log.info("上传成功：{}", dest.getAbsolutePath());
            }
            return Result.success(results);
        } catch (IOException e) {
            log.error("批量上传失败", e);
            return Result.fail("上传异常：" + e.getMessage());
        }
    }

    /**
     * 获取 resources/upload 路径
     */
    /**
     * 获取上传路径，使用项目运行目录，而不是resources
     */
    @SneakyThrows
    private String getUploadDir() {
        String uploadDir = "";
        if (WebMvcResourceEnum.isRunningInIDE()) {
            File path = new File(ResourceUtils.getURL("classpath:").getPath());
            File menu = new File(path, "upload");
            if (!menu.exists()) {
                menu.mkdirs();
            }
            uploadDir = menu.getPath();
        } else {
            uploadDir = System.getProperty("user.dir") + File.separator + "upload";
        }
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        log.info("上传文件路径={}", uploadDir);
        return uploadDir;
    }

    public static void main(String[] args) {
        System.out.println("args = " + System.getProperty("java.io.tmpdir"));
        System.out.println("args = " + System.getProperty("user.dir"));
    }
}
